﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Escape
{
    class Block
    {

        public bool solidRender = true;
        public bool collision = true;
        public bool sprite = false;
        public bool alterRendering = false;

        public float collisionDistanceX;
        public float collisionDistanceZ;

        public Vector3 rot = Vector3.Zero;

        private RasterizerState rs;
        private RasterizerState rsDefault = new RasterizerState();

        public Vector3 position;

        private bool removed = false;
        public Texture2D tex;

        public CullMode cm = CullMode.CullCounterClockwiseFace;

        public BoundingBox box;

        public void Update()
        {
            box = new BoundingBox(new Vector3(0, -1, 0), new Vector3(1, 0, 1));
            box.Max = Vector3.Transform(box.Max, Matrix.CreateTranslation(position));
            box.Min = Vector3.Transform(box.Min, Matrix.CreateTranslation(position));
        }

        public void remove()
        {
            removed = true;
        }

        public void loadTexture(String path)
        {
            tex = Basic.content.Load<Texture2D>(path);
        }

        public virtual void use() { }

        public virtual void onCollision()
        {
          
        }

        public bool isInBlock(Vector3 p)
        {
            if (removed)
                return false;
            if ((position.X - collisionDistanceX) < p.X && (position.X + 1.0f + collisionDistanceX) > p.X)
            {
                if ((position.Z + 1.0f + collisionDistanceZ) > p.Z && (position.Z - collisionDistanceZ) < p.Z)
                {
                    onCollision();
                    return true;
                }
            }

            return false;
        }

        public virtual void alterRender() { }

        public void Render()
        {
            Basic.device.DepthStencilState = DepthStencilState.Default;
            if ((sprite || alterRendering) && !removed)
            {
                alterRender();
                return;
            }

            if (!solidRender || removed)
                return;

            rs = new RasterizerState();
            rs.CullMode = cm;

            Basic.device.RasterizerState = rs;

            if (tex != null)
            {
                if (box.Intersects(GameScreen.c.getFrustum()))
                {
                    GameScreen.effect.TextureEnabled = true;
                    GameScreen.effect.Texture = tex;


                    GameScreen.cube.Draw(Matrix.CreateFromYawPitchRoll(rot.Y, rot.X, rot.Z) * Matrix.CreateTranslation(position));
                }
            }

            Basic.device.RasterizerState = rsDefault;
        }
    }

}
